package lws.com.liwushuo.view.fragment.shouye;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import lws.com.liwushuo.R;
import lws.com.liwushuo.adapter.shouye.SearchWordCompletedAdapter;
import lws.com.liwushuo.bean.shouye.SearchWordCompleteBean;
import lws.com.liwushuo.server.shouye.SearchServer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ZQ on 2016/10/17.
 */

public class SearchWordCompletedFragment extends Fragment implements Callback<SearchWordCompleteBean> {


    private View view;
    private RecyclerView wordCompleted;
    private SearchServer server;
    private String keyWord;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        //获取传过来的搜索关键字
        keyWord= arguments.getString("keyWord");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.shouye_search_wordcompleted_fragment, null);
        }
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        //获取控件
        wordCompleted = ((RecyclerView) view.findViewById(R.id.shouye_search_wordcompleted_listView));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        wordCompleted.setLayoutManager(layoutManager);
        //设置分割线
        // TODO: 2016/10/17 分割线没有设置好
//        wordCompleted.addItemDecoration(new MyDecoration(getContext(),LinearLayoutManager.VERTICAL));

        //请求网络,获取自动匹配的字符串
        server = new Retrofit.Builder()
                .baseUrl("http://api.liwushuo.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(SearchServer.class);
        //获取数据
        server.getWordCompleteBean(keyWord).enqueue(this);
    }

    /**
     * 网络回调
     */
    @Override
    public void onResponse(Call<SearchWordCompleteBean> call, Response<SearchWordCompleteBean> response) {
        List<String> words = response.body().getData().getWords();
        SearchWordCompletedAdapter searchWordCompletedAdapter = new SearchWordCompletedAdapter(getContext(), words);
        wordCompleted.setAdapter(searchWordCompletedAdapter);
    }

    @Override
    public void onFailure(Call<SearchWordCompleteBean> call, Throwable t) {
    }

}
